package net.oktaeder.office.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This class represents a collection of employees
 * 
 * @author tuukka
 *
 */
public class EmployeeCollection {

	private static Log log = LogFactory.getLog(EmployeeCollection.class);
	ArrayList<Employee> collection;
	
	/**
	 * Default constructor
	 *
	 */
	public EmployeeCollection() {
		collection = new ArrayList<Employee>();
	}
	
	/**
	 * 
	 * @return Iterator of internal collection, if collection has not been
	 *         set up, null is returned
	 */
	public Iterator<Employee> getIterator() {
		if (collection != null) {
			return collection.iterator();
		} else {
			return null;
		}
	}
	
	/**
	 * 
	 * @param worker Worker to be added to the collection
	 */
	public void addEmployee(Employee worker) {
		collection.add(worker);
	}
	
	/**
	 * 
	 * @param worker Worker to be removed from the collection
	 */
	public void removeEmployee(Employee worker) {
		collection.remove(worker);
	}
	
	/**
	 * Clears the collection
	 *
	 */
	public void clear() {
		collection.clear();
	}
	
	/**
	 * 
	 * @return Amount of workers in the collection
	 */
	public int amount() {
		return collection.size();
	}
	
	/**
	 * Search employee collection for a specific employee
	 * 
	 * @param PIN Personal Identification Number used in search
	 * @return Employee if found, otherwise null
	 */
	public Employee findByPIN(String PIN) {
		Iterator<Employee> iterator;
		Employee tempEmployee;
		
		try {
			iterator = collection.iterator();
			
			while (iterator.hasNext()) {
				tempEmployee = iterator.next();
				if (tempEmployee.getPIN().equals(PIN)) {
					return tempEmployee;
				}
			}
			
			return null;			
		} catch (Exception ex) {
			log.warn("Finding by PIN failed", ex);
			return null;
		}

	}

	/**
	 * Search employee collection for a specific employee
	 * 
	 * @param name Name of the employee to find
	 * @return List of employees, which may be empty if no match is found
	 */
	public List<Employee> findByName(String name) {
		Iterator<Employee> iterator;
		List<Employee> list;
		Employee tempEmployee;
		
		iterator = collection.iterator();
		list = new ArrayList<Employee>();
		
		while (iterator.hasNext()) {
			tempEmployee = iterator.next();
			if (tempEmployee.getName().equals(name)) {
				list.add(tempEmployee);
			}
		}
		
		return list;
	}	
}
